/**
 * 
 */
package com.java.realm;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.java.entity.Function;
import com.java.entity.Users;
import com.java.service.impl.FunctionServiceImpl;
import com.java.service.impl.UserServiceImpl;

/**
* @author Kidney
* 创建时间：2019年4月26日 上午3:12:45
* Description:
*/
/**
 * @author KIDNEY
 *
 */
public class AuthenRealms extends AuthorizingRealm {

	private static String  SALT = "siyuan";
	
	
	
	@Autowired 
	private UserServiceImpl us;
	
	@Autowired
	private FunctionServiceImpl fs;
	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//获取用户名名称
		String username = token.getPrincipal().toString();
		//通过用户名获取用户对象
		Users user = us.login(username, null);
		//把user对象封装的AuthenticationInfo中返回
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user,user.getPassword(),ByteSource.Util.bytes(SALT),"authenRealm");
		System.out.println(authenticationInfo.getCredentialsSalt());
		return authenticationInfo;
	}

	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//获取当前用户信息
		Users user = (Users)principals.getPrimaryPrincipal();
		List<String> perms = new ArrayList<String>();
		//List<String> roles = new ArrayList<String>();
		//根据用户信息获取所属于角色
		//根据角色查权限
		
		List<Function> functions = fs.findByUserId(user.getUserid());
		for(Function func : functions){
			perms.add(func.getFuncCode());
		}
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		//把所有的权限串列表都放到SimpleAuthorizationInfo对象中
		authorizationInfo.addStringPermissions(perms); 
		//authorizationInfo.addRoles(roles);//放置所有的角色信息
		
		return authorizationInfo;
	}

}
